package com.example.bluetooth_test;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Handler;
import android.print.PrinterId;

import java.io.IOException;
import java.util.UUID;

public class ClientThread extends Thread {

    private BluetoothSocket mSocket ;
    private final BluetoothDevice mDevice;
    private  BluetoothAdapter bluetoothAdapter;
    private final Handler handler;
    private ConnectedThread mConnect;

    private static final UUID MY_UUID = UUID.fromString(Constant.UUID);

    public ClientThread(BluetoothDevice device, Handler handler) {
        this.mDevice = device;
        this.handler = handler;

        //UI将一个临时的对象分配给mSocket, mSocket是最终的
        BluetoothSocket tmp = null;
        try {
            tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
        } catch (IOException e) {
            e.printStackTrace();
        }
        mSocket = tmp;
    }

    public void run(){
        //搜索占据资源太大，关掉以提高速度
       // bluetoothAdapter.cancelDiscovery();

        try {
            //通过Socket连接设备，阻塞运行直到成功或抛出异常，
            mSocket.connect();
        } catch (IOException e) {
            e.printStackTrace();
            //向UI——status提示Connection
            handler.sendMessage(handler.obtainMessage(Constant.STATE_CONNECTION_FAILED));
            try {
                mSocket.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            return;
        }
        //在单独的线程里完成管理链接的工作
        manageConnectedSocket(mSocket);
    }

    public void manageConnectedSocket(BluetoothSocket mSocket) {
        //发送给UI——status：Connected
        handler.sendMessage(handler.obtainMessage(Constant.STATE_CONNECTED));
        //开始发送和接受数据
        mConnect = new ConnectedThread(mSocket,handler);
        mConnect.start();
    }

    public void cancle() {
            try {
                mSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
    }

    public void write(byte[] bytes) {
        if (mConnect != null) {
            mConnect.write(bytes);
        }
    }
}
